package cn.com.ghy.android.widget.chat;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.com.ghy.android.bean.CustomerInfoBean;
import cn.com.ghy.android.bean.DataCollectDayInfoBean;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.OrderDetailBean;
import cn.com.ghy.android.bean.YeTaiTypeBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.CustOpeService;
import cn.com.ghy.android.service.OrderOpeService;
import cn.com.ghy.android.service.VisitOpeService;
import cn.com.ghy.android.style.MenuTabContent;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:客户信息列表
 * @author wuz  @date 2011-5-4 13:25:57
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class CustomerList extends Activity {

	private EditText txtCustomerNum = null;
	private EditText txtCustomerName = null;
	private Button btnCustomerListQuery = null;
	private ListView listView = null;
	private ProgressDialog progressDialog = null;
	private TextView labTxtCustomerCount = null;

	private CustomerListAdapter customerListAdapter = null;

	private LoginInfoBean loginInfo = null;
	private String customerNum = null;
	private String customerName = null;
	private Intent intent = null;

	@SuppressWarnings("unused")
	private static final String TAG = "CustomerList";
	private HttpThread thread = null;

	private List<OrderDetailBean> listOrderDetail = null;
	private CustomerInfoBean customerInfo = null;
	private Bundle bundle = null;

	private DisposeException disposeException = null;

	private MenuTabContent.MenuBodyAdapter bodyAdapter = null;
	private MenuTabContent tabMenu;
	private View appToolBar = null;
	private ImageButton btnList = null;
	private ImageButton btnBack = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.customer_list);
		getSession();
		setToolBar();
		setMenu();
		findView();
		addListener();
	}

	public void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfo = ((ComStaticApp) this.getApplication()).getLoginInfo();
	}

	private void setToolBar() {
		appToolBar = findViewById(R.id.appToolBar);
		btnList = (ImageButton) appToolBar.findViewById(R.id.btnList);
		btnBack = (ImageButton) appToolBar.findViewById(R.id.btnBack);
	}

	private void findView() {
		txtCustomerNum = (EditText) this.findViewById(R.id.txtCustomerNum);
		txtCustomerName = (EditText) this.findViewById(R.id.txtCustomerName);
		btnCustomerListQuery = (Button) this.findViewById(R.id.btnCustomerListQuery);
		listView = (ListView) this.findViewById(R.id.listCustomerList);
		labTxtCustomerCount = (TextView) this.findViewById(R.id.labTxtCustomerCount);
	}

	private void addListener() {
		btnCustomerListQuery.setOnClickListener(btnListener);
		btnBack.setOnClickListener(imgBtnListener);
		btnList.setOnClickListener(imgBtnListener);
	}

	private View.OnClickListener btnListener = new View.OnClickListener() {
		public void onClick(View v) {
			Button button = (Button) v;
			switch (button.getId()) {
				case R.id.btnCustomerListQuery :
					customerNum = txtCustomerNum.getText().toString().trim();
					customerName = txtCustomerName.getText().toString().trim();
					new CustomerInfoAsyncTask().doStart();
					listView.setOnItemClickListener(new CustomerListEvent());
					break;
			}
		}
	};

	private View.OnClickListener imgBtnListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			ImageButton imageButton = (ImageButton) v;
			switch (imageButton.getId()) {
				case R.id.btnList :
					openOptionsMenu();
					break;
				case R.id.btnBack :
					CustomerList.this.finish();
					break;
			}
		}
	};

	@SuppressWarnings("rawtypes")
	private class CustomerInfoAsyncTask extends AsyncTask {

		private List<CustomerInfoBean> list = null;

		@SuppressWarnings("unchecked")
		public void doStart() {
			progressDialog = new ProgressDialog(CustomerList.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			CustomerInfoAsyncTask.this.execute();
		}

		@Override
		protected Object doInBackground(Object... params) {
			try {
				CustOpeService service = new CustOpeService();
				list = service.GetCustList(customerNum, customerName, loginInfo);
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
			progressDialog.dismiss();
			listView.post(new Runnable() {
				public void run() {
					customerListAdapter = new CustomerListAdapter(CustomerList.this, list);
					listView.setAdapter(customerListAdapter);
					labTxtCustomerCount.setText(customerListAdapter.getCount() + "");
				}
			});
			return list;
		}
	}

	private class CustomerListAdapter extends BaseAdapter {

		private Context context = null;
		private List<CustomerInfoBean> list = new ArrayList<CustomerInfoBean>();

		public CustomerListAdapter(Context context, List<CustomerInfoBean> list) {
			this.context = context;
			this.list = list;
		}

		public int getCount() {
			return list.size();
		}

		public CustomerInfoBean getItem(int position) {
			return list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(inflater);
			LinearLayout linearLayout = null;
			if (list.get(position) instanceof CustomerInfoBean) {
				linearLayout = (LinearLayout) layoutInflater.inflate(R.layout.customer_list_lay,
						null);
				TextView textView = ((TextView) linearLayout.findViewById(R.id.labTxtCustomerNo));
				textView.setText((position + 1) + ".客户编号");

				textView = ((TextView) linearLayout.findViewById(R.id.labTxtCustomerId));
				textView.setText(list.get(position).getPartner());

				textView = ((TextView) linearLayout.findViewById(R.id.labTxtCustomerGrade));
				textView.setText(list.get(position).getDengji());

				textView = ((TextView) linearLayout.findViewById(R.id.labTxtCustomerName));
				textView.setText(list.get(position).getName_org1());

				textView = ((TextView) linearLayout.findViewById(R.id.labTxtCustomerContact));
				textView.setText(list.get(position).getLxr());

				textView = ((TextView) linearLayout.findViewById(R.id.labTxtCustomerPhone));
				textView.setText(list.get(position).getLxdh());

				textView = ((TextView) linearLayout.findViewById(R.id.labTxtCustomerAddress));
				textView.setText(list.get(position).getStreet());
			}
			return linearLayout;
		}

	}

	private class CustomerListEvent implements AdapterView.OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			CustomerListAdapter customerListAdapter = (CustomerListAdapter) (parent.getAdapter());
			showDialog(CustomerList.this, customerListAdapter.getItem(position));
		}
	}

	private void showDialog(Context context, final CustomerInfoBean customerInfo) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("提示信息");
		builder.setMessage("名称:" + customerInfo.getName_org1() + "\n编号:"
				+ customerInfo.getPartner());
		builder.setPositiveButton("查看客户", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String intentflag = "look";
				thread = new HttpThread(handler);
				thread.doStart(customerInfo, intentflag);
			}
		});
		builder.setNeutralButton("创建订单", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String intentflag = "create";
				thread = new HttpThread(handler);
				thread.doStart(customerInfo, intentflag);
			}
		});
		builder.setNegativeButton("上架SKU", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String intentflag = "sku";
				thread = new HttpThread(handler);
				thread.doStart(customerInfo, intentflag);
			}
		});
		builder.show();
	}

	private void setMenu() {
		bodyAdapter = new MenuTabContent.MenuBodyAdapter(this, new String[] { "新客户提报" },
				new int[] { R.drawable.menu_add }, 20, getResources().getColor(R.color.white));

		tabMenu = new MenuTabContent(this, new BodyClickEvent(), getResources().getColor(
				R.color.MenuBackGroundColor), R.style.PopupAnimation);

		tabMenu.update();
		tabMenu.SetBodyAdapter(bodyAdapter);
	}

	private class BodyClickEvent implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			tabMenu.SetBodySelect(position, Color.GRAY);
			switch (position) {
				case 0 :
					String intentflag = "new_customer";
					thread = new HttpThread(handler);
					thread.doStart(null, intentflag);
					break;
			}

			if (null != tabMenu) {
				if (tabMenu.isShowing()) {
					tabMenu.dismiss();
				}
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {//使用此方法调用系统菜单选项，onMenuOpened返回为true时触发
//		menu.add("menu");
//		menu.add("menu1");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {//打开菜单后发生的动作
		if (tabMenu != null) {
			if (tabMenu.isShowing()) {
				tabMenu.dismiss();
			} else {
				int toolBarHeight = appToolBar.getHeight();
				tabMenu.showAtLocation(findViewById(R.id.txtCustomerNum), Gravity.BOTTOM, 0,
						toolBarHeight);
			}
		}
		return true;
	}

	private class HttpThread extends Thread {

		private Handler handle = null;
		private CustomerInfoBean simpleCustomerInfo = null;
		private String intentflag = null;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		private void doStart(CustomerInfoBean simpleCustomerInfo, String intentflag) {
			this.simpleCustomerInfo = simpleCustomerInfo;
			this.intentflag = intentflag;
			progressDialog = new ProgressDialog(CustomerList.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Message message = null;
			try {
				if ("sku".equals(intentflag)) {
					VisitOpeService visitOpeService = new VisitOpeService();
					List<DataCollectDayInfoBean> dataCollectDayInfoList = visitOpeService
							.GetLastBismt(loginInfo, simpleCustomerInfo.getPartner());
					if (dataCollectDayInfoList.size() > 0) {
						progressDialog.dismiss();
						message = handle.obtainMessage();
						bundle = new Bundle();
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putString("intentflag", intentflag);
						bundle.putSerializable("customerInfo", simpleCustomerInfo);
						bundle.putSerializable("dataCollectDayInfoList",
								(Serializable) dataCollectDayInfoList);
					} else {
						progressDialog.dismiss();
						message = handle.obtainMessage();
						bundle = new Bundle();
						message.what = CommonStatic.STATE_NORMAL_NULL;
						bundle.putString("intentflag", intentflag);
					}
				} else if ("new_customer".equals(intentflag)) {
					CustOpeService service = new CustOpeService();
					List<YeTaiTypeBean> list = service.GetYt();
					progressDialog.dismiss();
					message = handle.obtainMessage();
					bundle = new Bundle();
					message.what = CommonStatic.STATE_NORMAL;
					bundle.putSerializable("listYeTaiType", (Serializable) list);
					bundle.putString("intentflag", intentflag);
				} else {
					CustOpeService service = new CustOpeService();
					List<CustomerInfoBean> list = service.GetCustShow(simpleCustomerInfo
							.getPartner());
					customerInfo = list.get(0);
					OrderOpeService orderOpeService = new OrderOpeService();
					listOrderDetail = orderOpeService.GetLastMatnr(simpleCustomerInfo.getPartner());
					progressDialog.dismiss();
					message = handle.obtainMessage();
					bundle = new Bundle();
					message.what = CommonStatic.STATE_NORMAL;
					bundle.putSerializable("customerInfo", customerInfo);
					bundle.putString("intentflag", intentflag);
					bundle.putSerializable("listOrderDetail", (Serializable) listOrderDetail);
				}
				message.setData(bundle);
				handle.sendMessage(message);
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
		}
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message m) {
			String intentflag = m.getData().getString("intentflag");
			customerInfo = (CustomerInfoBean) m.getData().getSerializable("customerInfo");
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					if ("sku".equals(intentflag)) {
						List<DataCollectDayInfoBean> dataCollectDayInfoList = (List<DataCollectDayInfoBean>) m
								.getData().getSerializable("dataCollectDayInfoList");
						bundle = new Bundle();
						bundle.putSerializable("dataCollectDayInfoList",
								(Serializable) dataCollectDayInfoList);
						bundle.putSerializable("customerInfo", customerInfo);
						intent = new Intent(CustomerList.this, LastBismt.class);
						intent.putExtras(bundle);
						CustomerList.this.startActivity(intent);
					} else if ("new_customer".equals(intentflag)) {
						List<YeTaiTypeBean> listYeTaiType = (List<YeTaiTypeBean>) m.getData()
								.getSerializable("listYeTaiType");
						bundle = new Bundle();
						bundle.putSerializable("listYeTaiType", (Serializable) listYeTaiType);
						intent = new Intent(CustomerList.this, NewCustomer.class);
						intent.putExtras(bundle);
						CustomerList.this.startActivity(intent);
					} else {
						listOrderDetail = (List<OrderDetailBean>) m.getData().getSerializable(
								"listOrderDetail");
						bundle = new Bundle();
						bundle.putSerializable("customerInfo", customerInfo);
						bundle.putSerializable("listOrderDetail", (Serializable) listOrderDetail);
						bundle.putString("intentflag", intentflag);
						if ("look".equals(intentflag)) {
							intent = new Intent(CustomerList.this, CustomerDetailInfoList.class);
						} else if ("create".equals(intentflag)) {
							intent = new Intent(CustomerList.this, OrderInfo.class);
						}
						intent.putExtras(bundle);
						CustomerList.this.startActivity(intent);
					}
					break;
				case CommonStatic.STATE_NORMAL_NULL :
					if ("sku".equals(intentflag)) {
						new AlertDialog.Builder(CustomerList.this).setTitle("提示信息")
								.setMessage("暂时没有上架SKU!").setNeutralButton("关闭", null).show();
					}
					break;
			}
		}
	};
}
